import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:package_info/package_info.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/entity/user_entity.dart';
import 'package:yp/http/upload_app_http.dart';
import 'package:yp/services/api.dart';

import 'config/config.dart';
import 'router.dart';
import 'state.dart';

/// 全局逻辑 用于获取用户状态、主题设置等信息
class GlobalLogic extends GetxController {
  final state = GlobalState();

  @override
  void onInit() {
    super.onInit();
    if (!kIsWeb) {
      _getVersionInfo();
    }
  }

  /// 更新用户信息
  void updateUser({UserEntity entity, String token, bool isBack = true}) {
    // 更新全局用户信息
    if (entity != null) {
      state.user = entity;
      // 缓存用户信息
      SpUtil.putObject(Config.USER_CACHE, entity.toJson());
    }

    // 缓存token
    if (token != null) SpUtil.putString(Config.TOKEN, token);

    // 返回
    update();
    if (isBack) Get.back();
  }

  /// 退出登陆
  void logout() {
    // SpUtil.remove(Config.TOKEN);
    // SpUtil.remove(Config.USER_CACHE);
    // SpUtil.remove('sid');
    var exist = SpUtil.getString("yes") == "a";
    var isAgree = SpUtil.getBool("isAgree") ?? false;
    SpUtil.clear();
    if (exist) {
      SpUtil.putString("yes", "a");
    }
    SpUtil.putBool("isAgree", isAgree);

    // 更新全局用户信息
    state.user = null;
    Get.offAllNamed(RouteConfig.main);
    update();
  }

  static getLoginScreenStyle() async {
    // if (GetPlatform.isAndroid) {
    //   Config.loginScreenStyle = '0';
    //   return;
    // }
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    var _ver = packageInfo.version ?? "";
    var _vername = "vip";
    //接口路径:com.ykcloud.soa.omp.basicdata.api.service.BdCommunityService.get.app.online.config传参实例:{"tenant_num_id":20,"data_sign":0,"app_version":"2.3.1","app_name":"vip"}
    var params = {
      "app_version": _ver,
      "app_name": _vername,
    };
    Api.getLoginScreenStyle(params).listen((event) {
      print('getLoginScreenStyle event:$event');
      if (event["code"] != 0) {
        Config.loginScreenStyle = '1';
      } else {
        Config.loginScreenStyle = event["online_value"];
      }
    });
  }

  void getVersion() {
    if (!kIsWeb) {
      CGHttpClient.getAppVersion((version) {
        state.versionNo = version;
      });
    }
  }

  void _getVersionInfo() {
    // var a =  SpUtil.getString('yes');
    // if(a != 'a'){
    //   return;
    // }
    CGHttpClient.startRequest(CGHttpClient.CGHSHUpdateVersion, {
      "appCode": CGHttpClient.UploadAppCode,
      'flag': Platform.isAndroid ? 'android' : 'ios'
    }, (code, data) {
      if (code == 0 && data['status'].toString() == '1') {
        var updateInfo = data['data'] as Map;
        SpUtil.putObject(CGHttpClient.VersionInfo, updateInfo);
      }
    });
  }
}
